﻿using Asp.Versioning;
using FlyingEye.Factories;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace FlyingEye.Controllers
{
    [Route("api/device-ops-service/v{version:apiVersion}/production-bases")]
    [ApiVersion("1.0")]
    [ControllerName("ProductionBase")]
    [Authorize]
    public class ProductionBaseController : DefaultController
    {
        private readonly IProductionBaseRepository _productionBaseRepository;

        private readonly IProductionWorkshopRepository _productionWorkshopRepository;

        public ProductionBaseController(
            IProductionBaseRepository productionBaseRepository,
            IProductionWorkshopRepository productionWorkshopRepository)
        {
            _productionBaseRepository = productionBaseRepository;
            _productionWorkshopRepository = productionWorkshopRepository;
        }

        [HttpGet]
        public async Task<ActionResult<List<ProductionBaseResponse>>> GetListAsync()
        {
            return await this.GetInvokeAsync(async () =>
            {
                var productionBases = await _productionBaseRepository.GetListAsync();
                return ObjectMapper.Map<List<ProductionBaseModel>, List<ProductionBaseResponse>>(productionBases);
            });
        }

        [HttpGet("{id}/production-workshops")]
        public async Task<ActionResult<List<ProductionWorkshopResponse>>> GetProductionWorkshopsAsync(int id)
        {
            return await this.GetInvokeAsync(async () =>
            {
                var productionWorkshops = await _productionWorkshopRepository.GetListAsync(item => item.SiteId == id);
                return ObjectMapper.Map<List<ProductionWorkshopModel>, List<ProductionWorkshopResponse>>(productionWorkshops);
            });
        }

        [HttpGet("{id}", Name = "GetByProductionBaseId")]
        public async Task<ActionResult<ProductionBaseResponse>> GetAsync(int id)
        {
            return await this.GetInvokeAsync(async () =>
            {
                var productionBase = await _productionBaseRepository.GetAsync(id);
                return ObjectMapper.Map<ProductionBaseModel, ProductionBaseResponse>(productionBase);
            });
        }

        [HttpPost]
        public async Task<ActionResult<ProductionBaseResponse>> InsertAsync([FromBody] CreateProductionBaseRequest request)
        {
            return await this.InsertInvokeAsync(async () =>
            {
                var productionBase = ObjectMapper.Map<CreateProductionBaseRequest, ProductionBaseModel>(request);
                productionBase = await _productionBaseRepository.InsertAsync(productionBase);
                return ObjectMapper.Map<ProductionBaseModel, ProductionBaseResponse>(productionBase);
            }, "GetByProductionBaseId", e => new { e.Id });
        }
    }
}
